# -*- coding: utf-8 -*-
"""
支付控制器

处理支付相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends, File, UploadFile, Form
from pydantic import BaseModel
from typing import Optional, Dict, Any
from app.controllers.user_controller import get_current_user
from app.services.payment_service import PaymentService
from app.services.order_status_service import OrderStatusService

# 创建支付路由
payment_router = APIRouter(
    prefix="/payments",
    tags=["payments"],
    responses={404: {"description": "Not found"}}
)

# 创建UniApp兼容路由
uniapp_payment_router = APIRouter(
    prefix="/uniapp/payments",
    tags=["uniapp-payments"],
    responses={404: {"description": "Not found"}}
)

# 初始化服务
payment_service = PaymentService()
order_status_service = OrderStatusService()


# ==================== 请求模型 ====================

class PaymentInitiateRequest(BaseModel):
    order_id: str
    payment_method: str


class PaymentCallbackRequest(BaseModel):
    payment_id: str
    transaction_id: Optional[str] = None
    status: str  # success/failed
    error_msg: Optional[str] = None


class ReceiptUploadRequest(BaseModel):
    order_id: str
    receipt_url: str
    notes: Optional[str] = None


# ==================== 标准API接口 ====================

@payment_router.get("/methods")
async def get_payment_methods(current_user = Depends(get_current_user)):
    """获取支付方式列表"""
    try:
        result = payment_service.get_payment_methods()
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取支付方式失败: {str(e)}")


@payment_router.post("/initiate")
async def initiate_payment(
    request: PaymentInitiateRequest,
    current_user = Depends(get_current_user)
):
    """发起支付"""
    try:
        user_id = current_user.get('user_id')
        result = payment_service.initiate_payment(
            request.order_id, 
            request.payment_method, 
            user_id
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发起支付失败: {str(e)}")


@payment_router.post("/callback")
async def payment_callback(request: PaymentCallbackRequest):
    """支付回调接口"""
    try:
        if request.status == "success":
            result = payment_service.handle_payment_success(
                request.payment_id, 
                request.transaction_id
            )
        else:
            result = payment_service.handle_payment_failure(
                request.payment_id, 
                request.error_msg
            )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result.get('data', {})
            }
        else:
            return {
                "code": 400,
                "message": result['message']
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"处理支付回调失败: {str(e)}"
        }


@payment_router.post("/receipt/upload")
async def upload_receipt(
    request: ReceiptUploadRequest,
    current_user = Depends(get_current_user)
):
    """上传支付回执"""
    try:
        user_id = current_user.get('user_id')
        result = payment_service.upload_payment_receipt(
            request.order_id,
            request.receipt_url,
            user_id,
            request.notes
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传回执失败: {str(e)}")


# ==================== UniApp兼容接口 ====================

@uniapp_payment_router.get("/methods")
async def uniapp_get_payment_methods(current_user = Depends(get_current_user)):
    """UniApp获取支付方式列表"""
    try:
        result = payment_service.get_payment_methods()
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "payment_methods": result['data'],
                    "total": len(result['data'])
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取支付方式失败: {str(e)}")


@uniapp_payment_router.post("/pay")
async def uniapp_pay(
    order_id: str = Form(...),
    payment_method: str = Form(...),
    current_user = Depends(get_current_user)
):
    """UniApp发起支付"""
    try:
        user_id = current_user.get('user_id')
        result = payment_service.initiate_payment(order_id, payment_method, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发起支付失败: {str(e)}")


@uniapp_payment_router.post("/receipt/upload")
async def uniapp_upload_receipt(
    order_id: str = Form(...),
    receipt_file: UploadFile = File(...),
    notes: Optional[str] = Form(None),
    current_user = Depends(get_current_user)
):
    """UniApp上传支付回执文件"""
    try:
        user_id = current_user.get('user_id')
        
        # 验证文件类型
        if not receipt_file.content_type.startswith('image/'):
            raise HTTPException(status_code=400, detail="只支持图片文件")
        
        # 保存文件 (这里需要实现文件保存逻辑)
        # 暂时使用模拟URL
        receipt_url = f"/static/receipts/{order_id}_{receipt_file.filename}"
        
        # TODO: 实际保存文件到静态目录
        # import os
        # os.makedirs("static/receipts", exist_ok=True)
        # with open(f"static/receipts/{order_id}_{receipt_file.filename}", "wb") as f:
        #     content = await receipt_file.read()
        #     f.write(content)
        
        result = payment_service.upload_payment_receipt(
            order_id, receipt_url, user_id, notes
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传回执失败: {str(e)}")


@uniapp_payment_router.get("/status/{order_id}")
async def uniapp_get_payment_status(
    order_id: str,
    current_user = Depends(get_current_user)
):
    """UniApp获取支付状态"""
    try:
        user_id = current_user.get('user_id')
        
        # 获取订单状态信息
        result = order_status_service.get_order_status_info(order_id, user_id)
        
        if result['success']:
            data = result['data']
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "order_id": order_id,
                    "status": data['current_status']['status'],
                    "status_info": data['current_status']['info'],
                    "payment_status": data['payment_status'],
                    "payment_type": data['payment_type'],
                    "updated_time": data['updated_time']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取支付状态失败: {str(e)}")


# ==================== 模拟支付页面 ====================

@payment_router.get("/demo/{payment_id}")
async def demo_payment_page(payment_id: str):
    """模拟支付页面（用于测试）"""
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>模拟支付页面</title>
        <meta charset="utf-8">
        <style>
            body {{ font-family: Arial, sans-serif; padding: 20px; }}
            .payment-form {{ max-width: 400px; margin: 0 auto; }}
            .form-group {{ margin-bottom: 15px; }}
            button {{ padding: 10px 20px; margin: 5px; cursor: pointer; }}
            .success {{ background-color: #4CAF50; color: white; }}
            .fail {{ background-color: #f44336; color: white; }}
        </style>
    </head>
    <body>
        <div class="payment-form">
            <h2>模拟支付</h2>
            <p>支付ID: {payment_id}</p>
            <div class="form-group">
                <button class="success" onclick="simulatePayment('success')">模拟支付成功</button>
                <button class="fail" onclick="simulatePayment('failed')">模拟支付失败</button>
            </div>
            <div id="result"></div>
        </div>
        
        <script>
        function simulatePayment(status) {{
            fetch('/payments/callback', {{
                method: 'POST',
                headers: {{
                    'Content-Type': 'application/json'
                }},
                body: JSON.stringify({{
                    payment_id: '{payment_id}',
                    transaction_id: 'TXN' + Date.now(),
                    status: status,
                    error_msg: status === 'failed' ? '模拟支付失败' : null
                }})
            }})
            .then(response => response.json())
            .then(data => {{
                document.getElementById('result').innerHTML = 
                    '<p>' + (data.code === 200 ? '✅ ' : '❌ ') + data.message + '</p>';
            }})
            .catch(error => {{
                document.getElementById('result').innerHTML = '<p>❌ 请求失败: ' + error + '</p>';
            }});
        }}
        </script>
    </body>
    </html>
    """
    
    from fastapi.responses import HTMLResponse
    return HTMLResponse(content=html_content) 